package com.bw.zhanggm.zyk.cart.controller;

import com.bw.zhanggm.zyk.cart.feign.ProductFeignClient;
import com.bw.zhanggm.zyk.cart.vo.Sku;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import org.apache.ibatis.mapping.ResultMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/cart/")
public class CartController {

    @Autowired
    HttpServletRequest request;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RedisService redisService;

    @Autowired
    ProductFeignClient productFeignClient;


    /**
     * 添加购物车
     * @param productId 商品Id
     * @param num 前端传数据,不考虑加+1，-1
     * @param from 来源，from=cart
     * @return
     */
    @GetMapping("add")
    public AjaxResult add(String productId,
                          @RequestParam(value = "num",defaultValue = "1") Integer num,
                          @RequestParam(value = "from",defaultValue = "") String from) {
        //登录的用户信息
        String userId = JwtUtils.getUserName(request.getHeader("Token"));
        //如果商品的数量==0，则从购物车删除
        if (num.equals(0)) {
            redisTemplate.opsForHash().delete("cart:" + userId, productId);
        }
        //添加购物车
        if ("cart".equals(from)) {
            redisTemplate.opsForHash().put("cart:" + userId, productId, num);
            return AjaxResult.success();
        }
        //其它页面加入购物车，如果购物车有商品，则在原来的数量上+num
        Integer oldNum = (Integer) redisTemplate.opsForHash().get("cart:" + userId, productId);
        if (oldNum != null) {
            num += oldNum;
        }
        redisTemplate.opsForHash().put("cart:" + userId, productId, num);
        return AjaxResult.success();
    }

    /**
     * 我的购物车
     * @return
     */
    @GetMapping("my")
    public AjaxResult my() {
        //登录的用户信息
        String userId = JwtUtils.getUserName(request.getHeader("Token"));
        //查询购物车数据
        Map<String,Integer> cartMap = redisTemplate.opsForHash().entries("cart:" + userId);
        if (cartMap == null || cartMap.isEmpty()) {
            return AjaxResult.success();
        }
        //查询商品信息
        Set<String> ProductIdSet = cartMap.keySet();
        final ArrayList<Sku> skuList = productFeignClient.getSkuListByIds(ProductIdSet);
        skuList.forEach(sku->{
            //计算小计
            sku.setNum(cartMap.get(sku.getId()+""));
            sku.setTotal(sku.getPrice().multiply(new BigDecimal(sku.getNum() + "")));
        });
        //计算总计
        double total = skuList.stream().mapToDouble(item -> item.getTotal().doubleValue()).sum();
        //返回结果
        Map<String, Object> reusltMap = new HashMap<>();
        reusltMap.put("productList", skuList);
        reusltMap.put("total", total);
        return AjaxResult.success(reusltMap);
    }


    @GetMapping("del")
    public AjaxResult del(String productId) {
        //登录的用户信息
        String userId = JwtUtils.getUserName(request.getHeader("Token"));
        redisTemplate.opsForHash().delete("cart:" + userId, productId);
        return AjaxResult.success();
    }


}
